package redisserver

import (
	"fmt"

	"codehub-g.huawei.com/videocloud/mediaprocesscenter/application-gateway/config"
	"codehub-g.huawei.com/videocloud/mediaprocesscenter/application-gateway/pkg/utils/log"
	"github.com/go-redis/redis/v7"
)

// Init init redis
func Init() error {
	RedisClient := GetRedisClient()
	rcd := RedisClient.Ping()
	if rcd.Val() != "PONG" {
		log.RunLogger.Errorf("test ping redis error: %+v, addr:%s, password: *********, DB: %d",
			rcd, config.GlobalConfig.RedisAddress, config.GlobalConfig.RedisDB)
		return fmt.Errorf("test ping redis error: %+v", rcd)
	}

	return nil
}

func GetRedisClient() *redis.Client {
	RedisClient := redis.NewClient(&redis.Options{
		Addr:     config.GlobalConfig.RedisAddress,
		Password: config.GlobalConfig.RedisPassword,
		DB:       config.GlobalConfig.RedisDB,
	})

	return RedisClient
}

func CloseRedisClient(client *redis.Client) {
	err := client.Close()
	if err != nil {
		log.RunLogger.Errorf("[Redis] close client error for %v", err)
	}
}
